<template>
  <div>
    <HeaderSelector></HeaderSelector>
    <div class="background">
      <div class="m-content">
        <el-card class="card">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <div class="input">
              <el-form-item label="标题" prop="title">
                <el-input v-model="ruleForm.title"></el-input>
              </el-form-item>

              <el-form-item label="摘要" prop="description">
                <el-input type="textarea" v-model="ruleForm.description"></el-input>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <!--引用富文本编辑器-->
                <!--步骤：1 npm install mavon-editor --save
                         2 main.js 导入
                         3 在此使用

                         ref在上传图片方法中  获取mv实体
                         详情见：https://gitee.com/zvlance/mavonEditor#%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0
                         https://juejin.cn/post/6885547864278827021
                        -->
                <mavon-editor v-model="ruleForm.content" ref="md" @imgAdd="imgAdd" @imgDel="$imgDel"></mavon-editor>
              </el-form-item>
            </div>
            <el-form-item class="m-button">
              <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

  </div>
</template>

<script>
import HeaderSelector from "../components/HeaderSelector";

export default {
  name: "BlogEdit.vue",
  components: {HeaderSelector},
  data() {
    return {
      ruleForm: {
        id: '',
        title: '',
        description: '',
        content: '',
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 3, max: 25, message: '长度在 3 到 25 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入摘要', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'blur'}
        ],
      },

    };
  },
  methods: {
    imgAdd(pos, file) {
      var formData = new FormData()
      formData.append('file', file);  //这里的key  file 要和后端贴切
      this.$axios({
        url: '/uploadImg',//输入上传的地址 或者公司的图床地址
        method: 'post',
        data: formData,    //new出来的
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        //这里图片已经上传了 只不过idea不能及时更新
        let url = res.data.data.url; //获取返回的url
        console.log("imgURL "+url);
        this.$refs.md.$imglst2Url([[pos, url]]);  //传入markdown 中 $imglst2Url为固定方法写法
      })
    },

    $imgDel(pos) {
      delete this.img_file[pos];
    },

    submitForm(formName) {
      //validate 前端验证 固定格式
      this.$refs[formName].validate((valid) => {
        if (valid) {

          const _this = this
          //此次操作需要 验证token
          this.$axios.post('/blog/edit', this.ruleForm, {
                headers: {
                  "Authorization": localStorage.getItem("token")
                }
              }
          ).then(res => {
            console.log(res)
            //这段js 是 elementUI格式
            _this.$alert('操作成功', '提示', {
              confirmButtonText: '确定',

              //分类添加 默认


              callback: action => {
                //确定后的操作
                _this.$router.push("/blog/"+res.data.data.id)
              }
            });

          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {
    //主要用于编辑时回显

    //之所以能拿到id  是因为路由请求的中（请求编辑中）包含了id
    const blogId = this.$route.params.blogId
    console.log(blogId)
    const _this = this
    //用于回显 文章内容（编辑模式：能够获取文章id的时候）  拿不到就不回显  又编辑请求来
    if (blogId) {
      this.$axios.get('/blog/' + blogId).then(res => {
        const blog = res.data.data
        _this.ruleForm.id = blog.id
        _this.ruleForm.title = blog.title
        _this.ruleForm.description = blog.description
        _this.ruleForm.content = blog.content
        _this.ruleForm.classification = blog.classification
      })
    }

  }
}
</script>

<style scoped>
.m-content {
  text-align: center;
  margin: auto;
  width: 70%;
}

.background {
  background-image: url("http://qtrqnpw61.hn-bkt.clouddn.com/%E8%83%8C%E6%99%AF2.png");
  position: relative;
  margin: auto;
  top: 50px;
}

.m-button {
  position: relative;
  right: 30px;
}

.input {
  position: relative;
  right: 20px;
}

.m-classify {
  text-align: left;
}
.demo-ruleForm {
  position: relative;
  top: 25px;
  right: 20px;
}

</style>